package com.itheima.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.QueryPageBean;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.ManagerUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @version V1.0
 * @author: TXT
 * @date: 2020/2/11 21:14
 * @description: 用户管理
 */
@RestController
@RequestMapping("managerUser")
public class ManagerUserController {

    @Reference
    private ManagerUserService managerUserService;

    /**
     * 分页查询所有用户
     *
     * @param queryPageBean
     * @return
     */

    @PreAuthorize("hasAuthority('ROLE_QUERY')")
    @RequestMapping("/findPage")
    @ResponseBody
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult page = null;
        try {
            page = managerUserService.findPage(queryPageBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return page;
    }

    @PreAuthorize("hasAuthority('USER_ADD')")
    @RequestMapping("addUser")
    @ResponseBody
    public Result addUser(@RequestBody User user) {
        try {
            managerUserService.addUser(user);
            return Result.success(true, "新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(false, "新增失败");
        }
    }

    @PreAuthorize("hasAuthority('ROLE_QUERY')")
    @RequestMapping("findUserById")
    @ResponseBody
    public Result findUserById(Integer id) {
        try {
            Map map = managerUserService.findUserById(id);
            return Result.success(true, "查询单个成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(false, "查询单个失败");
        }
    }

    @PreAuthorize("hasAuthority('USER_EDIT')")
    @RequestMapping("editUser")
    @ResponseBody
    public Result editUser(@RequestBody User user) {
        try {
            managerUserService.editUser(user);
            return Result.success(true, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(false, "修改失败");
        }
    }

    @PreAuthorize("hasAuthority('USER_DELETE')")
    @RequestMapping("deleteUser")
    @ResponseBody
    public Result deleteUser(Integer id) {
        try {
            managerUserService.deleteUser(id);
            return Result.success(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(false, "删除失败");
        }
    }
}
